import React from 'react'
import { Form, Input, Button, message } from 'antd'
import { useNavigate, Link } from 'react-router-dom'
import { apiRegister, apiCheckUsername } from '../../api/auth'
import '../login/Login.css'

type RegisterForm = {
  username: string
  password: string
  confirmPassword: string
}

function Register() {
  const navigate = useNavigate()

  const onFinish = async (values: RegisterForm) => {
    try {
      const payload = {
        ...values,
        // 后端需要 email，这里根据用户名自动生成占位邮箱
        email: `${values.username || 'user'}@auto.local`
      } as any
      const res = await apiRegister(payload)
      if (res.status === 201 || res.status === 200) {
        message.success(res.data?.message || '注册成功，请登录')
        navigate('/login')
      } else {
        message.error(res.data?.message || '注册失败')
      }
    } catch (e: any) {
      const msg = e?.response?.data?.message || '注册失败'
      message.error(msg)
    }
  }

  return (
    <div className="login-container">
      <div className="login-topbar">
        <div className="topbar-inner">
          <span className="topbar-title">数字人管理系统 · 注册</span>
        </div>
      </div>

      <div className="cyber-grid" />
      <div className="terrain" />

      <div className="meteors" aria-hidden>
        <span className="meteor"/>
        <span className="meteor"/>
        <span className="meteor"/>
        <span className="meteor"/>
        <span className="meteor"/>
        <span className="meteor"/>
        <span className="meteor"/>
        <span className="meteor"/>
        <span className="meteor"/>
        <span className="meteor"/>
        <span className="meteor"/>
        <span className="meteor"/>
        <span className="meteor near"/>
        <span className="meteor near"/>
        <span className="meteor near"/>
      </div>

      <div className="ripples" aria-hidden>
        <div className="ripple r1"></div>
        <div className="ripple r2"></div>
        <div className="ripple r3"></div>
      </div>

      <div className="login-card neon-circle">
        <div className="card-header minimal">
          <h1 className="login-title">欢迎注册</h1>
          <p className="login-subtitle">创建你的账户以进入系统</p>
        </div>

        <Form<RegisterForm> layout="vertical" onFinish={onFinish} autoComplete="off" className="login-form">
          <Form.Item<RegisterForm>
            name="username"
            label="用户名"
            validateTrigger="onBlur"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, message: '至少 3 个字符' },
              {
                validator: async (_, value) => {
                  if (!value) return Promise.resolve()
                  const res = await apiCheckUsername(value)
                  const exists = res.data?.data?.exists
                  if (exists) return Promise.reject(new Error('用户名已存在'))
                  return Promise.resolve()
                }
              }
            ]}
          >
            <div className="input-container">
              <Input placeholder="请输入用户名" className="login-input" />
              <div className="input-glow"></div>
            </div>
          </Form.Item>

          

          <Form.Item<RegisterForm> name="password" label="密码" rules={[{ required: true, message: '请输入密码' }, { min: 6, message: '至少 6 个字符' }]}>
            <div className="input-container">
              <Input.Password placeholder="请输入密码" className="login-input" />
              <div className="input-glow"></div>
            </div>
          </Form.Item>

          <Form.Item<RegisterForm> name="confirmPassword" label="确认密码" dependencies={["password"]} rules={[{ required: true, message: '请再次输入密码' }, ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) return Promise.resolve()
              return Promise.reject(new Error('两次输入的密码不一致'))
            }
          })]}>
            <div className="input-container">
              <Input.Password placeholder="请再次输入密码" className="login-input" />
              <div className="input-glow"></div>
            </div>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" className="login-button" block>注册</Button>
          </Form.Item>
          <div className="auth-tip">
            已有账号？<Link to="/login">去登录</Link>
          </div>
        </Form>
      </div>
    </div>
  )
}

export default Register
